package com.xzzz.expand.es.core;

import com.xzzz.common.base.exception.XzException500;
import com.xzzz.expand.es.core.common.EsConstants;
import com.xzzz.expand.es.core.dto.EsInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.MainResponse;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;

/**
 * @author xzzz
 * 
 */
@Slf4j
public class AbstractEsManager {

    /**
     * 连接客户端
     */
    protected final RestHighLevelClient client;

    /**
     * ES 配置文件信息
     */
    protected final EsProperties esProperties;

    /**
     * 构造方法
     */
    public AbstractEsManager(RestHighLevelClient restHighLevelClient, EsProperties esProperties) {
        this.client = restHighLevelClient;
        this.esProperties = esProperties;
    }

    /**
     * 获取 high client
     * @return RestHighLevelClient
     */
    public final RestHighLevelClient getHighClient () {
        return client;
    }

    /**
     * 获取ES信息
     *
     * <code>GET host:port</code>
     *
     * @return ES信息
     */
    public final EsInfoDTO getInfo() {
        EsInfoDTO info = new EsInfoDTO();

        EsInfoDTO.EsTool esTool = new EsInfoDTO.EsTool();
        esTool.setDescription(EsConstants.EsTool.DESCRIPTION);
        esTool.setVersion(EsConstants.EsTool.VERSION);
        info.setEsTool(esTool);

        try {
            MainResponse response = client.info(RequestOptions.DEFAULT); // 返回集群的各种信息
            info.setClusterName(response.getClusterName());              // 集群名称
            info.setClusterUuid(response.getClusterUuid());              // 群集的唯一标识符
            info.setNodeName(response.getNodeName());                    // 已执行请求的节点的名称
            info.setVersion(response.getVersion());                      // 已执行请求的节点的版本
            return info;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return info;
    }

    /**
     * ES 异常翻译
     * @param e ES 异常信息
     */
    protected void esExceptionSuppose(ElasticsearchStatusException e) {
        e.printStackTrace();
        if (e.status().equals(RestStatus.NOT_FOUND) && e.getDetailedMessage().contains("type=index_not_found_exception")) {
            throw new XzException500(String.format("没有找到对应的索引 [%s], 请检查是否正确, 或是否需要[*]通配索引", e.getIndex().getName()));
        }

    }

}
